package com.heima.search.listener;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.heima.common.exception.CustomException;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.constants.ArticleConstants;
import com.heima.model.search.vo.SearchArticleVo;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @projectName: heima-leadnews
 * @package: com.heima.search.listener
 * @className: ArticleEsListener
 * @author: 躺着认真玩
 * @description: 接收发布文章并存储到Es中
 * @date: 2025/5/28 8:31
 * @version: 1.0
 */
@Component
public class ArticleEsListener {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @KafkaListener(topics = ArticleConstants.ARTICLE_ES_SYNC_TOPIC)
    public void articleEsListener(String message) throws IOException {
        // 校验参数
        if (StrUtil.isBlank(message)) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // es存储
        SearchArticleVo bean = JSONUtil.toBean(message, SearchArticleVo.class);
        IndexRequest request = new IndexRequest("app_article").id(String.valueOf(bean.getId()));
        request.source(bean, XContentType.JSON);
        // 发送请求
        restHighLevelClient.index(request, RequestOptions.DEFAULT);
        return;
    }
}
